package droideep.library.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by bri on 15-4-24.
 */
public class TagStrip extends LinearLayout {

    private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
    private static final float TAB_VIEW_TEXT_SIZE_SP = 12;
    private static final float TAB_VIEW_PADDING_DIPS = 16;

    private final int mDefaultBottomBorderColor;
    private final Paint mBottomBorderPaint;

    private int mSelectedPosition;
    protected String[] mTags;
    private int mTabViewLayoutId;
    private int mTabViewTextViewId;
    private boolean mDistributeEvenly = true;
    private SparseArray<String> mContentDescriptions = new SparseArray<String>();

    private TabPositionListener mPositionListener;

    private TabColorizer mTabColorizer;

    public TagStrip(Context context) {
        this(context, null);
    }

    public TagStrip(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);

        final float density = getResources().getDisplayMetrics().density;

        TypedValue outValue = new TypedValue();
        context.getTheme().resolveAttribute(android.R.attr.colorForeground, outValue, true);
        final int themeForegroundColor = outValue.data;

        mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);

        mBottomBorderPaint = new Paint();
        mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        final int height = getHeight();
        final int childCount = getChildCount();
        if (childCount > 0) {
            View selectedView = getChildAt(mSelectedPosition);
            int left = selectedView.getLeft();
            int right = selectedView.getRight();
        }

        canvas.drawRect(0, height, getWidth(), height, mBottomBorderPaint);
    }

    /**
     * Set the alpha value of the {@code color} to be the given {@code alpha} value.
     */
    private int setColorAlpha(int color, byte alpha) {
        return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
    }

    public void setTags(String[] tags) {
        this.removeAllViews();
        mTags = tags;
        if (mTags != null && mTags.length > 0) {
            populateTabStrip();
        }
    }

    public boolean isDistributeEvenly() {
        return mDistributeEvenly;
    }

    public void setDistributeEvenly(boolean distributeEvenly) {
        this.mDistributeEvenly = distributeEvenly;
    }

    public TabPositionListener getPositionListener() {
        return mPositionListener;
    }

    public void setPositionListener(TabPositionListener positionListener) {
        this.mPositionListener = positionListener;
    }

    private void populateTabStrip() {
        final OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < mTags.length; i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set,try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, this, false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            if (mDistributeEvenly) {
                LinearLayout.LayoutParams lp = (LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            tabTitleView.setText(mTags[i]);
            tabTitleView.setTextColor(Color.WHITE);
            tabView.setTag(Integer.valueOf(i));
            tabView.setOnClickListener(tabClickListener);
            String desc = mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            this.addView(tabView);
        }
    }

    private View createDefaultTabView(Context context) {
        TextView textView = new TextView(context);
        textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        TypedValue outValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
        textView.setBackgroundResource(outValue.resourceId);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            textView.setAllCaps(true);
        }
        int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
        textView.setPadding(padding, padding, padding, padding);
        return textView;
    }

    /**
     * Set the custom layout to be inflated for the tab views.
     *
     * @param layoutResId Layout id to be inflated
     * @param textViewId  id of the {@link android.widget.TextView} in the inflated view
     */
    public void setCustomTabView(int layoutResId, int textViewId) {
        mTabViewLayoutId = layoutResId;
        mTabViewTextViewId = textViewId;
    }

    public void setCustomTabColorizer(TabColorizer tabColorizer) {
        mTabColorizer = tabColorizer;
    }

    private class TabClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            if (mPositionListener != null) {
                mPositionListener.onTab((Integer) v.getTag());
            }

            if (mTabColorizer != null) {
                mTabColorizer.tabColorizer(v);
            }
        }
    }

    public interface TabPositionListener {
        void onTab(int position);
    }

    public interface TabColorizer {
        void tabColorizer(View view);
    }
}
